package com.miraclemiles.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsUtils;

import com.miraclemiles.constant.SecurityConstants;
import com.miraclemiles.vo.LoginUser;

@EnableAutoConfiguration(exclude = UserDetailsServiceAutoConfiguration.class) // 排除内存用户的自动配置
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	
	@Resource
	private ResourceServerProperties resource;
	@Resource
	private RemoteTokenServices remoteTokenServices;

	/** 当前资源服务器的一些配置, 如资源服务器ID **/
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
		// 配置当前资源服务器的ID, 会在认证服务器验证(客户端表的resources配置了就可以访问这个服务)
		resources.resourceId(resource.getResourceId()).tokenServices(remoteTokenServices);
	}
	
	@Bean
	public DefaultAccessTokenConverter accessTokenConverter() {
		DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
		accessTokenConverter.setUserTokenConverter(new UserAuthenticationConverter() {
			@Override
			public Authentication extractAuthentication(Map<String, ?> map) {
				if (map.containsKey(USERNAME)) {
					Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
					String username = (String) map.get(USERNAME);
					Integer id = (Integer) map.get(SecurityConstants.DETAILS_USER_ID);
					Integer deptId = (Integer) map.get(SecurityConstants.DETAILS_DEPT_ID);
					Integer employeeId = (Integer) map.get(SecurityConstants.DETAILS_EMPLOYEE_ID);
					String email = (String) map.get(SecurityConstants.DETAILS_EMAIL);
					String mobile = (String) map.get(SecurityConstants.DETAILS_MOBILE);
					
					LoginUser user = new LoginUser((long)id, (long)deptId, (long)employeeId, email, mobile, username, "N/A", true, true, true, true, authorities);
					
					return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
				}
				return null;
			}
			
			@Override
			public Map<String, ?> convertUserAuthentication(Authentication authentication) {
				Map<String, Object> response = new LinkedHashMap<String, Object>();
				response.put(USERNAME, authentication.getName());
				if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
					response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
				}
				return response;
			}
			
			private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
				if (!map.containsKey(AUTHORITIES)) {
					return new ArrayList<SimpleGrantedAuthority>();
				}
				Object authorities = map.get(AUTHORITIES);
				if (authorities instanceof String) {
					return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
				}
				if (authorities instanceof Collection) {
					return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
							.collectionToCommaDelimitedString((Collection<?>) authorities));
				}
				throw new IllegalArgumentException("Authorities must be either a String or a Collection");
			}
		});
		
		return accessTokenConverter;
	}
	

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and()
				// 请求权限配置
				.authorizeRequests()
				// 下边的路径放行,不需要经过认证
				 .antMatchers("/test/**", "/oauth/**", "/user/**", "/actuator/**", "/error", "/open-api").permitAll()
				// OPTIONS请求不需要鉴权
				 .antMatchers(HttpMethod.OPTIONS).permitAll().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()

				// 其余接口没有角色限制，但需要经过认证，只要携带token就可以放行
				.anyRequest().authenticated();

	}

}
